/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.refactor;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Query;
import com.intellij.codeInsight.intention.IntentionAction;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Iterator;

public class InlineReturnIntention extends BaseIntention {

    private PsiLocalVariable psiLocalVariable;

    @NotNull
    public String getText() {
        return "Replace this variable with returns";
    }

    @NotNull
    public String getFamilyName() {
        return "RefactoringHelpers";
    }

    public boolean isAvailable(Project project, Editor editor, PsiFile psifile) {
        PsiElement element = getElement(editor, psifile);
        if (element instanceof PsiIdentifier) {
            PsiIdentifier psiIdentifier = (PsiIdentifier) element;
            PsiElement parent = psiIdentifier.getParent();
            if (parent instanceof PsiLocalVariable) {
                return checkLocalVariable((PsiLocalVariable) parent);
            } else if (parent instanceof PsiReferenceExpression) {
                PsiReferenceExpression psiReferenceExpression = (PsiReferenceExpression) parent;
                PsiElement psiElement = psiReferenceExpression.resolve();
                if (psiElement instanceof PsiLocalVariable) {
                    return checkLocalVariable((PsiLocalVariable) psiElement);
                }
            }
        }
        return false;
    }

    public void invoke(Project project, Editor editor, PsiFile psifile) throws IncorrectOperationException {
        try {
            PsiManager manager = psiLocalVariable.getManager();
            PsiElementFactory elementFactory = manager.getElementFactory();
            Query<PsiReference> query = ReferencesSearch.search(psiLocalVariable, psiLocalVariable.getUseScope(), false);
            Collection<PsiReference> all = query.findAll();
            for (PsiReference reference : all) {
                PsiElement element = ((PsiReferenceExpression) reference).getParent();
                if (element instanceof PsiAssignmentExpression) {
                    PsiAssignmentExpression assExp = (PsiAssignmentExpression) element;
                    PsiExpressionStatement assStat = (PsiExpressionStatement) element.getParent();
                    PsiExpression rExpression = assExp.getRExpression();
                    String returnValue = rExpression == null ? "null" : rExpression.getText();
                    PsiStatement statementFromText = elementFactory.createStatementFromText("return " + returnValue + ";", element);
                    assStat.replace(statementFromText);
                } else if (element instanceof PsiReturnStatement) {
                    PsiExpression initializer = psiLocalVariable.getInitializer();
                    if (initializer == null) {
                        element.delete();
                    } else {
                        PsiStatement statementFromText = elementFactory.createStatementFromText("return " + initializer.getText() + ";", element);
                        element.replace(statementFromText);
                    }

                }

            }
            psiLocalVariable.delete();
        } catch (IncorrectOperationException e) {
            throw new RuntimeException(e);
        }
    }

    private boolean checkLocalVariable(PsiLocalVariable psiLocalVariable) {
        int returnCount = 0;
        Query<PsiReference> query = ReferencesSearch.search(psiLocalVariable, psiLocalVariable.getUseScope(), true);
        Collection<PsiReference> all = query.findAll();
        for (PsiReference reference : all) {
            if (reference instanceof PsiReferenceExpression) {
                PsiReferenceExpression referenceExpression = (PsiReferenceExpression) reference;
                PsiElement parent = referenceExpression.getParent();
                if (parent instanceof PsiReturnStatement) {
                    returnCount++;
                    continue;
                }
                if (parent instanceof PsiAssignmentExpression) {
                    continue;
                }
            }
            return false;
        }
        if (returnCount == 1) {
            this.psiLocalVariable = psiLocalVariable;
            return true;
        }
        return false;
    }
}
